<template>
  <div class="users-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="手机"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template #default="{ row }">
            <el-switch v-model="row.mg_state" @change="changeSwitch(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div class="actions">
              <el-button
                type="success"
                icon="el-icon-edit"
                circle
                size="small"
                @click="getUsers(row.id)"
              ></el-button>
              <el-button
                type="primary"
                icon="el-icon-delete"
                size="small"
                circle
                @click="delUsers(row.id)"
              ></el-button>
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  icon="el-icon-setting"
                  circle
                  size="small"
                  @click="setRoles(row)"
                ></el-button>
              </el-tooltip>
            </div> </template
        ></el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="changePage"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addClose"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClose"
    >
      <el-form
        :model="editForm"
        ref="editForm"
        label-width="70px"
        :rules="editRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="rolesDialogVisible"
      width="50%"
      @close="roleClose"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="seveRoseInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { updateListState, userList } from "@/api/list";
import { Message } from "element-ui";
import { addUser, delUser, editUser, getUser, seveRoes } from "@/api/user";
import { getRolesList } from "@/api/roles";

export default {
  name: "userList",
  data() {
    const checkEmail = (rule, val, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(val)) {
        callback();
      } else {
        callback(new Error("请输入正确的邮箱"));
      }
    };
    const checkMobile = (rule, val, callback) => {
      const regMobile = /^1[3-9]\d{9}$/;
      if (regMobile.test(val)) {
        callback();
      } else {
        callback(new Error("请输入正确的手机号"));
      }
    };
    return {
      tableData: [],
      pagesize: 2,
      currentPage: 1,
      total: 1,
      query: "",
      addDialogVisible: false,
      editDialogVisible: false,
      rolesDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId: "",
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {},
      addRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "请输入3-10个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            pattern: /^\w{6,15}$/,
            message: "请输入6-15位密码",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    async getUsersList() {
      const res = await userList({
        pagenum: this.currentPage,
        pagesize: this.pagesize,
        query: this.query,
      });
      // console.log(res);
      this.total = res.data.total;
      this.tableData = res.data.users;
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.getUsersList();
    },
    changePage(page) {
      this.currentPage = page;
      this.getUsersList();
    },
    async changeSwitch(row) {
      try {
        await updateListState(row.id, row.mg_state);
        Message.success("更新成功");
      } catch (err) {
        Message.error("更新失败");
        row.mg_state = !row.row.mg_state;
      }
    },
    addClose() {
      this.$refs.addForm.resetFields();
    },
    editClose() {
      this.$refs.editForm.resetFields();
    },
    async addUser() {
      await this.$refs.addForm.validate();
      try {
        const res = await addUser(this.addForm);
        // console.log(res);
        if (res.meta.status === 201) {
          this.$message.success("用户创建成功");
          this.getUsersList();
        } else {
          this.$message.error(res.meta.msg);
        }
      } catch (err) {
        console.log(err);
        this.$message.error("用户创建失败");
      }
      this.$refs.addForm.resetFields();
      this.addDialogVisible = false;
    },
    async getUsers(id) {
      this.editDialogVisible = true;
      try {
        const res = await getUser(id);
        console.log(res);
        this.editForm = res.data;
      } catch (err) {
        // console.log(err);
        this.$message.error("获取个人用户信息失败");
      }
    },
    async editUsers() {
      await this.$refs.editForm.validate();
      try {
        const res = await editUser(this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        });
        if (res.meta.status === 200) {
          this.$message.success("用户更新成功");
          this.getUsersList();
        } else {
          this.$message.error(res.meta.msg);
        }
      } catch (err) {
        // console.log(err);
        this.$message.error("用户更新失败");
      }
      this.editDialogVisible = false;
      this.$refs.editForm.resetFields();
    },
    async delUsers(id) {
      const resConfrm = await this.$confirm(
        "此操作将删除该该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (resConfrm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const res = await delUser(id);
      if (res.meta.status === 200) {
        this.$message.success("删除成功");
        this.getUsersList();
      } else {
        this.$message.error(res.meta.msg);
      }
      this.currentPage = 1;
      this.getUsersList();
    },
    async setRoles(row) {
      this.rolesDialogVisible = true;
      this.userInfo = row;
      const res = await getRolesList();
      // console.log(res);
      if (res.meta.status === 200) {
        this.rolesList = res.data;
      } else {
        this.$message.error("获取失败");
      }
    },
    async seveRoseInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色");
      }
      const res = await seveRoes(this.userInfo.id, this.selectedRoleId);
      console.log(res);
      if (res.meta.status === 200) {
        this.$message.success("角色更新成功");
      } else {
        this.$message.error(res.meta.msg);
      }
      this.getUsersList();
      this.rolesDialogVisible = false;
    },
    roleClose() {
      (this.userInfo = {}), (this.selectedRoleId = "");
    },
  },
};
</script>

<style lang="scss" scoped>
.users-page {
  .el-breadcrumb {
    margin-bottom: 15px;
  }
  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;
    .el-table {
      margin-top: 20px;
      .actions {
        font-size: 18px;
        display: flex;
        justify-content: space-around;
        color: #666;
        > i:hover {
          color: rgba(114, 124, 245, 1);
          cursor: pointer;
        }
      }
    }
  }
}
</style>
